package database;

import java.sql.*;

public class MySQL {

    public static void main(String[] args) {
        // MySQL数据库连接信息
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "123456"; // 修改为你的MySQL密码

        // JDBC连接对象
        Connection conn = null;
        try {
            // 注册JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 打开连接
            System.out.println("连接到数据库...");
            conn = DriverManager.getConnection(url, username, password);

            // 执行查询
            String sql = "SELECT * FROM users";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            // 处理结果集
            while (rs.next()) {
                int id = rs.getInt(1);
                String usernameResult = rs.getString(2);
                String email = rs.getString(3);

                System.out.println("ID: " + id + ", Username: " + usernameResult + ", Email: " + email);
                System.out.println("ID: " + id + ", Username: " + usernameResult + ", Email: " + email);
                System.out.println("ID: " + id + ", Username: " + usernameResult + ", Email: " + email);
                System.out.println("ID: " + id + ", Username: " + usernameResult + ", Email: " + email);
                System.out.println("ID: " + id + ", Username: " + usernameResult + ", Email: " + email);
                System.out.println("ID: " + id + ", Username: " + usernameResult + ", Email: " + email);
                System.out.println("ID: " + id + ", Username: " + usernameResult + ", Email: " + email);
                System.out.println("ID: " + id + ", Username: " + usernameResult + ", Email: " + email);
            }

            // 关闭资源
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            // 处理JDBC异常
            se.printStackTrace();
        } catch (Exception e) {
            // 处理Class.forName异常
            e.printStackTrace();
        } finally {
            // 关闭连接
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("查询完成！");
    }
}
